package com.okex.demo.repository;

import com.okex.demo.model.OrderInfo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Repository
public interface OrderRepository extends JpaRepository<OrderInfo, Long> {
    
    // 查询所有订单
    List<OrderInfo> findAllByOrderByCreateTimeDesc();
    
    // 根据产品ID查询订单
    List<OrderInfo> findByInstIdOrderByCreateTimeDesc(String instId);
    
    // 根据时间范围查询所有订单
    @Query("SELECT o FROM OrderInfo o WHERE o.createTime BETWEEN :startDate AND :endDate ORDER BY o.createTime DESC")
    List<OrderInfo> findByDateRange(@Param("startDate") Date startDate, @Param("endDate") Date endDate);
    
    // 根据产品ID和时间范围查询订单
    @Query("SELECT o FROM OrderInfo o WHERE o.instId = :instId AND o.createTime BETWEEN :startDate AND :endDate ORDER BY o.createTime DESC")
    List<OrderInfo> findByInstIdAndDateRange(
            @Param("instId") String instId,
            @Param("startDate") Date startDate,
            @Param("endDate") Date endDate);
    
    // 删除指定时间范围内的所有订单
    @Modifying
    @Transactional
    @Query("DELETE FROM OrderInfo o WHERE o.createTime BETWEEN :startDate AND :endDate")
    int deleteByDateRange(@Param("startDate") Date startDate, @Param("endDate") Date endDate);
    
    // 删除指定产品ID和时间范围内的订单
    @Modifying
    @Transactional
    @Query("DELETE FROM OrderInfo o WHERE o.instId = :instId AND o.createTime BETWEEN :startDate AND :endDate")
    int deleteByInstIdAndDateRange(
            @Param("instId") String instId,
            @Param("startDate") Date startDate,
            @Param("endDate") Date endDate);
    
    // 查询当天的所有订单
    @Query("SELECT o FROM OrderInfo o WHERE FUNCTION('DATE', o.createTime) = FUNCTION('DATE', CURRENT_DATE) ORDER BY o.createTime DESC")
    List<OrderInfo> findTodayOrders();
} 